<!--
  组件名称：
  -->
<template>
  <div class="auto-scroller" ref="scroller" :style="{ height }" @mouseover="handleOver" @mouseout="handleOut">
    <div v-show="showCopy" class="copy-scroll" ref="copyScroller">
      <slot></slot>
    </div>
    <div v-show="scroller1Html" class="copy-scroll" ref="scroller1" v-html="scroller1Html"></div>
    <div v-show="scroller1Html" class="copy-scroll" ref="scroller2" v-html="scroller2Html"></div>
  </div>
</template>
<script>
export default {
  name: 'AutoScroller',
  props: {
    height: {
      type: String,
      default: '100%'
    }
  },
  data () {
    return {
      showCopy: false,
      scroller1Html: '',
      scroller2Html: '',
      timer: null,
      scroller: null,
      scroller1: null,
      scroller2: null,
      speed: 60
    }
  },
  mounted () {
    this.initScroll()
  },
  beforeDestroy () {
    this.clear()
  },
  methods: {
    clear () {
      this.timer && window.clearInterval(this.timer)
    },
    initScroll () {
      this.showCopy = true
      this.clear()
      this.$nextTick(() => {
        this.scroller = this.$refs.scroller
        this.scroller1 = this.$refs.scroller1
        this.scroller2 = this.$refs.scroller2
        const copyScroller = this.$refs.copyScroller
        const children = this.$slots.default[0].elm
        if (this.scroller.clientHeight < children.clientHeight) {
          this.showCopy = false
          this.scroller1Html = copyScroller.innerHTML
          this.scroller2Html = copyScroller.innerHTML
          this.timer = window.setInterval(this.marquee, this.speed)
        } else {
          this.scroller1Html = ''
          this.scroller2Html = ''
          this.showCopy = true
        }
        this.showCopy = true
      })
    },
    handleOver () {
      this.clear()
    },
    handleOut () {
      this.timer = window.setInterval(this.marquee, this.speed)
    },
    marquee () {
      if (this.scroller2.offsetHeight - this.scroller.scrollTop <= 0) {
        this.scroller.scrollTop -= this.scroller1.offsetHeight
      } else {
        this.scroller.scrollTop++
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .auto-scroller {
    overflow: hidden;
  }
</style>
